package controller

import (
	"errors"
	"github.com/labstack/echo"
	"github.com/sirupsen/logrus"
	"net/http"
	"src/config"
	"src/model"
	"src/util/context"
	"src/util/log"
	"strings"
)

var NoticeLogger = log.GetLogger()

func writeNoticeLoggerLoggerLog(funcName, errMsg string, err error) {
	NoticeLogger.WithFields(logrus.Fields{
		"package":  config.LogMessage,
		"file":     "notice.go",
		"function": funcName,
		"err":      err,
	}).Warn(errMsg)
}

func CreatNotice(c echo.Context) error {
	Notice := CreateNoticeParam{}
	_ = c.Bind(&Notice)
	if Notice.Content == "" {
		writeNoticeLoggerLoggerLog("CreatNotice", "Content为空", errors.New("Content为空"))
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, "Content为空")
	}
	Contents := strings.Split(Notice.Content, "\n")
	notice, err := model.CreatNotice(Contents)
	if err != nil {
		writeNoticeLoggerLoggerLog("CreatNotice", err.Error(), err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, err.Error())
	}
	return context.RetData(c, notice)
}

func ChangeNotice(c echo.Context) error {
	Notice := ChangeNoticeParam{}
	_ = c.Bind(&Notice)
	if Notice.Id == "" || Notice.Content == "" {
		writeNoticeLoggerLoggerLog("ChangeNotice", "id/Content为空", errors.New("id/Content为空"))
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, "id/Content为空")
	}
	Contents := strings.Split(Notice.Content, "\n")
	err := model.ChangeNotice(Notice.Id, Contents)
	if err != nil {
		writeNoticeLoggerLoggerLog("ChangeNotice", err.Error(), err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, err.Error())
	}
	return context.RetData(c, "")
}

func GetNoticeAll(c echo.Context) error {
	data, err := model.GetNoticeAll()
	if err != nil {
		writeNoticeLoggerLoggerLog("GetNoticeAll", err.Error(), err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, err.Error())
	}
	return context.RetData(c, data)
}

func GetNewNotice(c echo.Context) error {
	data, err := model.GetNewNotice()
	if err != nil {
		writeNoticeLoggerLoggerLog("GetNewNotice", err.Error(), err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, err.Error())
	}
	return context.RetData(c, data)
}

func DeleteNotice(c echo.Context) error {
	notice := DeleteNoticeParam{}
	_ = c.Bind(&notice)
	if notice.Id == "" {
		writeNoticeLoggerLoggerLog("DeleteNotice", "id为空", errors.New("id为空"))
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, "id为空")
	}
	err := model.DeleteNotice(notice.Id)
	if err != nil {
		writeNoticeLoggerLoggerLog("DeleteNotice", err.Error(), err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, err.Error())
	}
	return context.RetData(c, "")
}
